package com.music.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.RemoteException;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.music.R;
import com.music.ui.adapter.BoardMusicListAdapter;
import com.music.entity.BoardInfo;
import com.music.entity.BoardListInfo;
import com.music.entity.MusicInfo;
import com.music.entity.online.OnlineMusicInfo;
import com.music.entity.online.SongPlay;
import com.music.loader.Api;
import com.music.loader.DataRequest;
import com.music.service.MusicUtil;
import com.music.utils.Utility;
import com.music.ui.view.utils.LoadStateUtil;
import com.music.ui.view.utils.StateEnum;
import com.windy.xlistview.XListView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by dingfeng on 2016/9/21.
 */
public class BoardMusicListActivity extends BaseActivity {
    private TextView txtTitle;
    private View mHeader;
    private ImageView board_bg;
    private TextView txtComment;
    private XListView mListView;
    private LinearLayout loading;
    private LinearLayout loadFail;

    private BoardMusicListAdapter mAdapter;
    private BoardListInfo boardListInfo;
    private List<OnlineMusicInfo> mOnlineMusicList = new ArrayList<>();

    private static int size = 30;
    private int offset = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_board_music);
        initView();
        handleIntent(getIntent());
    }

    private void initView() {
        findViewById(R.id.back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        loading = (LinearLayout) findViewById(R.id.loading);
        loadFail = (LinearLayout) findViewById(R.id.loadFail);
        txtTitle = (TextView) findViewById(R.id.txtTitle);
        mListView = (XListView) findViewById(R.id.listView);
        mHeader = LayoutInflater.from(this).inflate(R.layout.header_board_muisc_list, null);
        board_bg = (ImageView) mHeader.findViewById(R.id.board_bg);
        txtComment = (TextView) mHeader.findViewById(R.id.txtComment);
        AbsListView.LayoutParams params = new AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, Utility.dp2px(150));
        mHeader.setLayoutParams(params);
        initListView();
        LoadStateUtil.stateChange(mListView, loading, loadFail, StateEnum.LOADING);
    }

    private void initListView() {
        mListView.addHeaderView(mHeader);
        mListView.setOnItemClickListener(onItemClickListener);
        mListView.setPullLoadEnable(true);
        mListView.setPullRefreshEnable(false);
        mListView.setXListViewListener(new XListView.IXListViewListener() {

            @Override
            public void onRefresh() {

            }

            @Override
            public void onLoadMore() {
                getOnlineMusic();
            }
        });

        mAdapter = new BoardMusicListAdapter(BoardMusicListActivity.this, mOnlineMusicList);
        mListView.setAdapter(mAdapter);
    }

    private void handleIntent(Intent intent) {
        boardListInfo = (BoardListInfo) intent.getSerializableExtra("board_type");
        if (boardListInfo != null) {
            txtTitle.setText(boardListInfo.getTitle());
            Glide.with(this)
                    .load(boardListInfo.getCoverBig())
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .into(board_bg);
            txtComment.setText(boardListInfo.getComment());
            getOnlineMusic();
        } else {
            LoadStateUtil.stateChange(mListView, loading, loadFail, StateEnum.LOAD_FAIL);
        }
    }

    private void getOnlineMusic() {
        DataRequest.getInstance().getBoardMusicList(Api.METHOD_GET_MUSIC_LIST,
                boardListInfo.getType(), size, offset, new DataRequest.Callback<BoardInfo>() {
            @Override
            public void onSuccess(BoardInfo data) {
                if (data != null && data.getOnlineMusicList() != null) {
                    List<OnlineMusicInfo> list = data.getOnlineMusicList();
                    if (list.size() < size) {
                        mListView.setPullLoadEnable(false);
                    } else {
                        offset = offset + size;
                    }
                    mOnlineMusicList.addAll(list);
                    mAdapter.notifyDataSetChanged();
                }
                mListView.stopLoadMore();
                LoadStateUtil.stateChange(mListView, loading, loadFail, StateEnum.LOAD_SUCCESS);
            }

            @Override
            public void onError(String err) {
                mListView.stopLoadMore();
                LoadStateUtil.stateChange(mListView, loading, loadFail, StateEnum.LOAD_FAIL);
            }
        });
    }

    AdapterView.OnItemClickListener onItemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            int realPos = position - 2;
            if (realPos < 0) return;
            OnlineMusicInfo onlineMusicInfo = mOnlineMusicList.get(realPos);
            playOnline(onlineMusicInfo);
        }
    };

    private void playOnline(final OnlineMusicInfo onlineMusicInfo) {
        DataRequest.getInstance().getOnlineUri(Api.METHOD_DOWNLOAD_MUSIC,
                onlineMusicInfo.getSongId(), new DataRequest.Callback<SongPlay>() {
            @Override
            public void onSuccess(SongPlay data) {
                if (data != null && data.getBitrate() != null) {
                    SongPlay.Bitrate bitrate = data.getBitrate();
                    final MusicInfo music = new MusicInfo();
                    music.setMusicName(onlineMusicInfo.getTitle());
                    music.setArtist(onlineMusicInfo.getArtistName());
                    music.setCover(onlineMusicInfo.getPicBig());
                    music.setData(bitrate.getFilelink());
                    music.setDuration(bitrate.getFileDuration() * 1000);
                    try {
                        MusicUtil.sService.playOnline(music);
                    } catch (RemoteException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onError(String err) {

            }
        });
    }

}
